package com.education.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;
import java.time.Duration;

/**
 * 使用redis做json数据序列化
 * Created by Lance on 2020/07/03 16:58
 */
@EnableCaching  // 开启redis缓存
@Configuration
public class RedisConfig {

    /**
     * 将默认的 jdk 序列化方式的转为json的方式系列化
     * @param connectionFactory 数据库连接工厂
     * @return
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        // 将 value 序列化
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        // 将 key 序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());//key序列化方式
        // 将值由默认的jdk 转为 json的方式序列化方式
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//value序列化
        // 使用 connectionFactory 工厂来创建数据库连接池
        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                //redis缓存过期时间600秒
                .entryTtl(Duration.ofSeconds(600))
                // 将 kye 系列化成 string
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                // 将值序列化成json
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                // 防止空值穿透, 将空值直接删除
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

}
